package cn.turboinfo.fuyang.api.gateway.mini.framework.http;

import cn.turboinfo.fuyang.api.gateway.mini.framework.http.fo.MiniRestResponseFO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import nxcloud.ext.springmvc.automapping.spring.AutoMappingRequestParameterTypeBinding;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.annotation.Annotation;

@Slf4j
@RequiredArgsConstructor
@RestControllerAdvice(basePackages = "cn.turboinfo.fuyang.api.gateway.mini.controller")
public class MiniResponseBodyWrapperAdvice implements ResponseBodyAdvice<Object> {

    private static final Class<? extends Annotation> ANNOTATION_TYPE = MiniResponseBodyWrapper.class;

    private final AutoMappingRequestParameterTypeBinding autoMappingRequestParameterTypeBinding;

    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(), ANNOTATION_TYPE) ||
                returnType.hasMethodAnnotation(ANNOTATION_TYPE) ||
                // 处理
                (returnType.getMethod() != null
                        && returnType.getContainingClass().getCanonicalName().startsWith("cn.turboinfo.fuyang.api.domain.mini")
                        && autoMappingRequestParameterTypeBinding.isSupportedMethod(returnType.getMethod()))
                ;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 防止重复包裹的问题出现
        if (body instanceof MiniRestResponseFO) {
            return body;
        }
        MiniRestResponseFO fo = MiniRestResponseFO.ok(body);
        if (body instanceof String) {
            // 如果返回是字符串在这里直接序列化好, 否则会转换错误
            try {
                return objectMapper.writeValueAsString(fo);
            } catch (JsonProcessingException e) {
                log.error("序列化出错, body=" + body, e);
                return fo;
            }
        }
        return fo;
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
}
